package entityAdapter

import (
	"fmt"
	"gitee.com/fierce_wolf/go-fox-edge-common/commConfig"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntity"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntityManager"
	"gitee.com/fierce_wolf/go-fox-edge-common/commSql"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Number"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEntity"
	"time"
)

type DeviceHistoryAdapter struct {
	lastTime int64
}

func (e *DeviceHistoryAdapter) SaveHistoryEntity(existValue commEntity.IEntity, statusValues map[string]interface{}) {
	// 定义一个最终的异常拦截，用来防止可能的代码BUG
	defer func() {
		if r := recover(); r != nil {
		}
	}()

	if existValue == nil {
		return
	}

	// 检查：是否需要记录
	configs, err := commConfig.GetConfigParam("serverConfig")
	if err != nil {
		return
	}
	deviceHistory := Map.GetMap(configs, "deviceHistory", make(map[string]interface{}))
	if !Map.GetBool(deviceHistory, "enable", false) {
		return
	}

	existValueEntity := existValue.(*edgeEntity.DeviceValueEntity)

	for paramName, paramValue := range statusValues {
		if !edgeEntity.Type.DeviceHistoryEntity.IsValue(paramValue) {
			continue
		}

		// 检查：数据是否发生了变化
		if !e.isChanged(existValueEntity, paramName, paramValue) {
			continue
		}

		// 构造历史记录对象
		deviceHistoryEntity := edgeEntity.Type.DeviceHistoryEntity.Instance()
		deviceHistoryEntity.DeviceId = existValueEntity.BaseEntity.Id
		deviceHistoryEntity.ObjectName = paramName
		deviceHistoryEntity.ParamValue = paramValue
		deviceHistoryEntity.BaseEntity.CreateTime = time.Now().UnixMilli()

		// 保存历史记录
		err := commSql.InsertEntity(deviceHistoryEntity)
		if err != nil {
			return
		}
	}
}

func (e *DeviceHistoryAdapter) isChanged(existValueEntity *edgeEntity.DeviceValueEntity, paramName string, paramValue interface{}) bool {
	if existValueEntity == nil {
		return true
	}

	existValue := existValueEntity.Params[paramName]
	if existValue == nil {
		return true
	}

	if paramValue == nil {
		return false
	}

	return paramValue != existValue.Value
}

func (e *DeviceHistoryAdapter) ClearHistoryEntity() {
	// 定义一个最终的异常拦截，用来防止可能的代码BUG
	defer func() {
		if r := recover(); r != nil {
		}
	}()

	if !commEntityManager.EntityManager.Initialized {
		return
	}

	configs, err := commConfig.GetConfigParam("serverConfig")
	if err != nil {
		return
	}

	value := Map.GetOrDefault(configs, "deviceHistory", make(map[string]interface{}))
	params := value.(map[string]interface{})

	maxCount := Number.MakeInt64(Map.GetOrDefault(params, "maxCount", 1000000))
	period := Number.MakeInt64(Map.GetOrDefault(params, "period", 3600))

	// 检查：执行周期是否到达
	currentTime := time.Now().UnixMilli()
	if (currentTime - e.lastTime) < period*1000 {
		return
	}
	e.lastTime = currentTime

	// 除了最近的maxCount条数据，旧数据全部删除
	e.deleteDeviceHistory(maxCount)
}

func (e *DeviceHistoryAdapter) deleteDeviceHistory(retainCount int64) {
	// 查询记录数量
	sumCount, err := commSql.Client.QueryCount("SELECT COUNT(1) FROM  tb_device_history")
	if err != nil {
		return
	}
	if int64(sumCount) <= retainCount {
		return
	}

	// 执行SQL删除语句
	sql := fmt.Sprintf("DELETE FROM  tb_device_history order BY id LIMIT  %v", int64(sumCount)-retainCount)
	commSql.Client.Exec(sql, nil)

	// 如果是sqlite，那么还要执行压缩命令
	if commSql.GetDBType() == "sqlite3" {
		commSql.Client.Exec("VACUUM;", nil)
	}
}
